<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="isEdit = false; doAdd(1, '0')">添加权限</el-button>
        </div>
        <el-table border :data="list" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button
                v-if="scope.row.type === 1"
                type="text"
                @click="isEdit = false; doAdd(2, scope.row.id)"
              >添加</el-button>
              <el-button type="text" @click="doEdit(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="doDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <el-dialog
      :visible.sync="showDialog"
      :title="(isEdit ? '编辑' : '新增') + '权限'"
      @close="doClose"
    >
      <!-- 表单内容 -->
      <el-form ref="perFormRef" label-width="100px" :model="perForm" :rules="perFormRules">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="perForm.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="perForm.code" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input v-model="perForm.description" />
        </el-form-item>
        <el-form-item label="权限启用">
          <el-switch
            v-model="perForm.enVisible"
            active-text="启用"
            active-value="1"
            inactive-text="不启用"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: center">
          <el-button type="primary" @click="submitPer">确定</el-button>
          <el-button @click="doClose">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getPermissionList, addPermission, delPermission, getPermissionDetail, updatePermission } from '@/api/permissions'
import { arrayToTree } from '@/utils'
export default {
  name: 'Permission',
  data() {
    // code自定义规则
    const validCode = (rule, value, callback) => {
      let codeList = this.originList.map(item => item.code)
      if (this.isEdit) {
        codeList = this.originList.filter(item => item.id !== this.perForm.id).map(item => item.code)
      }
      if (codeList.includes(value)) {
        callback(new Error(`${value}已经被占用`))
      } else {
        callback()
      }
    }
    // name自定义规则
    const validName = (rule, value, callback) => {
      let nameList = this.originList.filter(item => item.pid === this.perForm.pid).map(item => item.name)
      if (this.isEdit) {
        nameList = this.originList(item => item.pid === this.perForm.pid && item.id !== this.perForm.id).map(item => item.name)
      }
      if (nameList.includes(value)) {
        callback(new Error(`${value}已经被占用`))
      } else {
        callback()
      }
    }
    return {
      // 权限列表
      list: [],
      showDialog: false,
      perForm: {
        name: '', // 权限名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: null // 类型
      },
      perFormRules: {
        name: [
          { message: '权限名称不能为空', required: true, trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { message: '权限标识不能为空', required: true, trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        description: [
          { message: '权限描述不能为空', required: true, trigger: 'blur' }
        ]
      },
      isEdit: false,
      originList: []
    }
  },
  created() {
    this.loadPermissionList()
  },
  // methods:事件处理函数
  methods: {
    // 加载权限列表
    async loadPermissionList() {
      const res = await getPermissionList()
      this.list = arrayToTree(res.data.data, '0')
      this.originList = res.data.data
    },
    // 添加权限弹窗
    doAdd(type, pid) {
      this.showDialog = true
      this.perForm.type = type
      this.perForm.pid = pid
    },
    // 添加权限
    submitPer() {
      this.$refs.perFormRef.validate(async valid => {
        if (valid) {
          if (this.isEdit) {
            await updatePermission(this.perForm)
            this.showDialog = false
            this.loadPermissionList()
          } else {
            await addPermission(this.perForm)
            this.showDialog = false
            this.loadPermissionList()
          }
        } else {
          this.$message.error('表单校验不通过')
        }
      })
    },
    // 关闭弹窗
    doClose() {
      this.showDialog = false
      this.perForm = {
        name: '', // 权限名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: null // 类型
      }
    },
    // 删除权限节点
    async doDel(id) {
      this.$confirm('你确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delPermission(id)
        this.loadPermissionList()
      }).catch(() => {})
    },
    // 编辑权限节点
    async doEdit(id) {
      this.isEdit = true
      this.showDialog = true
      const res = await getPermissionDetail(id)
      this.perForm = { ...res.data.data }
    }
  }
}
</script>
